<?php
defined('IN_IA') or exit('Access Denied');
function m($name = '')
{
    static $_modules = array();
    if (isset($_modules[$name])) {
        return $_modules[$name];
    }
    $model =  "../addons/xuan_zyy/inc/model/" . strtolower($name) . '.php';
    if (!is_file($model)) {
        die(' Model ' . $name . ' Not Found!');
    }
    require $model;
    $class_name      = 'Xuan_zyy_' . ucfirst($name);
    $_modules[$name] = new $class_name();
    return $_modules[$name];
}



function is_weixin()
{
    if (empty($_SERVER['HTTP_USER_AGENT']) || strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') === false && strpos($_SERVER['HTTP_USER_AGENT'], 'Windows Phone') === false) {
        return false;
    }
    return true;
}

/**
 * 友好的时间显示
 *
 * @param int    $sTime 待显示的时间
 * @param string $type  类型. normal | mohu | full | ymd | other
 * @param string $alt   已失效
 * @return string
 */
function friendlyDate($sTime,$type = 'normal',$alt = 'false') {
    if (!$sTime)
        return '';
    //sTime=源时间，cTime=当前时间，dTime=时间差
    $cTime      =   time();
    $dTime      =   $cTime - $sTime;
    $dDay       =   intval(date("z",$cTime)) - intval(date("z",$sTime));
    //$dDay     =   intval($dTime/3600/24);
    $dYear      =   intval(date("Y",$cTime)) - intval(date("Y",$sTime));
    //normal：n秒前，n分钟前，n小时前，日期
    if($type=='normal'){
        if( $dTime < 60 ){
            if($dTime < 10){
                return '刚刚';    //by yangjs
            }else{
                return intval(floor($dTime / 10) * 10)."秒前";
            }
        }elseif( $dTime < 3600 ){
            return intval($dTime/60)."分钟前";
        //今天的数据.年份相同.日期相同.
        }elseif( $dYear==0 && $dDay == 0  ){
            //return intval($dTime/3600)."小时前";
            return '今天'.date('H:i',$sTime);
        }elseif($dYear==0){
            return date("m月d日 H:i",$sTime);
        }else{
            return date("Y-m-d H:i",$sTime);
        }
    }elseif($type=='mohu'){
        if( $dTime < 60 ){
            return $dTime."秒前";
        }elseif( $dTime < 3600 ){
            return intval($dTime/60)."分钟前";
        }elseif( $dTime >= 3600 && $dDay == 0  ){
            return intval($dTime/3600)."小时前";
        }elseif( $dDay > 0 && $dDay<=7 ){
            return intval($dDay)."天前";
        }elseif( $dDay > 7 &&  $dDay <= 30 ){
            return intval($dDay/7) . '周前';
        }elseif( $dDay > 30 ){
            return intval($dDay/30) . '个月前';
        }
    //full: Y-m-d H:i:s
    }elseif($type=='full'){
        return date("Y-m-d H:i:s",$sTime);
    }elseif($type=='ymd'){
        return date("Y-m-d",$sTime);
    }else{
        if( $dTime < 60 ){
            return $dTime."秒前";
        }elseif( $dTime < 3600 ){
            return intval($dTime/60)."分钟前";
        }elseif( $dTime >= 3600 && $dDay == 0  ){
            return intval($dTime/3600)."小时前";
        }elseif($dYear==0){
            return date("Y-m-d H:i:s",$sTime);
        }else{
            return date("Y-m-d H:i:s",$sTime);
        }
    }
}

if (!function_exists('redis')) {
    function redis()
    {
        global $_W;
        static $redis;

        if (is_null($redis)) {
            if (!extension_loaded('redis')) {
                return error(-1, 'PHP 未安装 redis 扩展');
            }

            if (!isset($_W['config']['setting']['redis'])) {
                return error(-1, '未配置 redis, 请检查 data/config.php 中参数设置');
            }

            $config = $_W['config']['setting']['redis'];

            if (empty($config['server'])) {
                $config['server'] = '127.0.0.1';
            }

            if (empty($config['port'])) {
                $config['port'] = '6379';
            }

            $redis_temp = new Redis();

            if ($config['pconnect']) {
                $connect = $redis_temp->pconnect($config['server'], $config['port'], $config['timeout']);
            }
            else {
                $connect = $redis_temp->connect($config['server'], $config['port'], $config['timeout']);
            }

            if (!$connect) {
                return error(-1, 'redis 连接失败, 请检查 data/config.php 中参数设置');
            }

            if (!empty($config['requirepass'])) {
                $redis_temp->auth($config['requirepass']);
            }

            try {
                $ping = $redis_temp->ping();
            }
            catch (ErrorException $e) {
                return error(-1, 'redis 无法正常工作，请检查 redis 服务');
            }

            if ($ping != '+PONG') {
                return error(-1, 'redis 无法正常工作，请检查 redis 服务');
            }

            $redis = $redis_temp;
        }
        else {
            try {
                $ping = $redis->ping();
            }
            catch (ErrorException $e) {
                $redis = NULL;
                $redis = redis();
                $ping = $redis->ping();
            }

            if ($ping != '+PONG') {
                $redis = NULL;
                $redis = redis();
            }
        }

        return $redis;
    }
}

function show_json($status = 1, $return = NULL)
{
    $ret = array('status' => $status, 'result' => $status == 1 ? array('url' => referer()) : array());

    if (!is_array($return)) {
        if ($return) {
            $ret['result']['message'] = $return;
        }

        exit(json_encode($ret));
    }
    else {
        $ret['result'] = $return;
    }

    if (isset($return['url'])) {
        $ret['result']['url'] = $return['url'];
    }
    else {
        if ($status == 1) {
            $ret['result']['url'] = referer();
        }
    }

    exit(json_encode($ret));
}
/*
 * #0000转换rgb
 */
function hex2rgb( $colour ) {
    if ( $colour[0] == '#' ) {
        $colour = substr( $colour, 1 );
    }
    if ( strlen( $colour ) == 6 ) {
        list( $r, $g, $b ) = array( $colour[0] . $colour[1], $colour[2] . $colour[3], $colour[4] . $colour[5] );
    } elseif ( strlen( $colour ) == 3 ) {
        list( $r, $g, $b ) = array( $colour[0] . $colour[0], $colour[1] . $colour[1], $colour[2] . $colour[2] );
    } else {
        return false;
    }
    $r = hexdec( $r );
    $g = hexdec( $g );
    $b = hexdec( $b );
    return array( 'r' => $r, 'g' => $g, 'b' => $b );
}

function curl_file_get_contents($durl){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $durl);
    curl_setopt($ch, CURLOPT_TIMEOUT, 2);
    curl_setopt($ch, CURLOPT_USERAGENT, _USERAGENT_);
    curl_setopt($ch, CURLOPT_REFERER,_REFERER_);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $r = curl_exec($ch);
    curl_close($ch);
    return $r;
}

function fenyong($money,$uid,$config,$type,$idd){
    global $_W;
	//自己信息
	$me=pdo_fetch("SELECT * FROM ".tablename("xuan_zy_person")." WHERE uid=:id ",array(":id"=>$uid));
	//上级
	$userup=m('member')->getup($uid);

	$slevel=m('member')->getlevel($userup['suid']);
	$sslevel=m('member')->getlevel($userup['ssuid']);
	$ssslevel=m('member')->getlevel($userup['sssuid']);

	$selfmoney=0;
	$smoney=0;
	$ssmoney=0;
	$sssmoney=0;

	$stc=getrate($me['level'],$slevel,$config);
	if($me['level']>$slevel['level']){
		$sstc=getrate($me['level'],$sslevel,$config);
		if($me['level']>$sslevel['level']){
			$ssstc=getrate($me['level'],$ssslevel,$config);
		}else{
			$ssstc=getrate($sslevel['level'],$ssslevel,$config);
		}

	}else{
		$sstc=getrate($slevel['level'],$sslevel,$config);
		if($slevel['level']>$sslevel['level']){
			$ssstc=getrate($slevel['level'],$ssslevel,$config);
		}else{
			$ssstc=getrate($sslevel['level'],$ssslevel,$config);
		}
	}



	/*var_dump($stc);
	var_dump($sstc);
	var_dump($ssstc);die;返佣百分比调试输出*/

	$smoney=$money*$stc/100;
	$ssmoney=$money*$sstc/100;
	$sssmoney=$money*$ssstc/100;
	if($me['level']==1){
		//专员
		$selfmoney=$money*$config['zy_tc2']/100;
		$sssmoney=0;
	}elseif($me['level']==2){
		//经理
		$selfmoney=$money*$config['jl_bk']/100;
		$sssmoney=0;
	}elseif($me['level']==3){
		//银行家
		$selfmoney=$money*$config['yhj_bk']/100;
		$sssmoney=0;
	}elseif($me['level']==0){
		//普通用户
		$selfmoney=0;
	}
	/*var_dump($selfmoney);
	var_dump($smoney);
	var_dump($ssmoney);
	var_dump($sssmoney);*/

	load()->model('mc');
	$name1=$type==1?'信用卡':'贷款';
	//开启事务
try {
	pdo_begin();
	if($selfmoney){
		mc_credit_update($me['uid'], 'credit2', $selfmoney, array(0));
		$data1 = array(
			'uid'=>$uid,
			'src_text'=>'收入',
			'data_name'=>'自己办理'.$name1.'提成',
			'src'=>$type,
			'order_money'=>$money,
			'type_text'=>'提成',
			'money'=>$selfmoney,
			'create_time'=>date('Y-m-d H:m:s',time()),
			'uniacid' => $me['uniacid'],
		);
		pdo_insert('xuan_zy_money', $data1);

		//有没有冻结插入过
		$dj=pdo_fetch("SELECT * FROM ".tablename('xuan_zy_dongjie').' where uniacid=:uniacid and uid=:uid ',array(':uid'=>$me['uid'],':uniacid'=>$_W['uniacid']));
		if(empty($dj)){
			$data10 = array(
				'uid'=>$uid,
				'money'=>$selfmoney,
				'create_time'=>time(),
				'uniacid' => $me['uniacid'],
			);
			pdo_insert('xuan_zy_dongjie', $data10);
		}



	}
	if($smoney && $userup['suid']){
		mc_credit_update($userup['suid'], 'credit2', $smoney, array(0));
		$data2 = array(
			'uid'=>$userup['suid'],
			'src_text'=>'收入',
			'data_name'=>'下级办理'.$name1.'提成',
			'src'=>$type,
			'order_money'=>$money,
			'type_text'=>'提成',
			'money'=>$smoney,
			'create_time'=>date('Y-m-d H:m:s',time()),
			'uniacid' => $me['uniacid'],
		);
		pdo_insert('xuan_zy_money', $data2);

        /*********发送提醒**********/
        $data  = array(
            "first"=>array( "value"=> '您的下级办理了'.$name1.'，您获得了'.$smoney.'元的提成奖励！已到账，请查收！'),
            "keyword1"=>array('value' =>$smoney),
            "keyword2"=>array('value' =>date('Y-m-d H:m:s')),
            "remark"=>array('value' => ""),
        );
        $openid=m('member')->getopenid($userup['suid']);

        $account = WeAccount:: create($_W['acid']);//$this->createMobileUrl('person',array('op'=>'comein')
        $a = $account->sendTplNotice($openid['openid'], $config['tpl_notice4'], $data,'');

        /*********发送结束**********/
	}
	if($ssmoney && $userup['ssuid']){
		mc_credit_update($userup['ssuid'], 'credit2', $ssmoney, array(0));
		$data3 = array(
			'uid'=>$userup['ssuid'],
			'src_text'=>'收入',
			'data_name'=>'下级办理'.$name1.'提成',
			'src'=>$type,
			'order_money'=>$money,
			'type_text'=>'提成',
			'money'=>$ssmoney,
			'create_time'=>date('Y-m-d H:m:s',time()),
			'uniacid' => $me['uniacid'],
		);
		pdo_insert('xuan_zy_money', $data3);

        /*********发送提醒**********/
        $data  = array(
            "first"=>array( "value"=> '您的下级办理了'.$name1.'，您获得了'.$ssmoney.'元的提成奖励！已到账，请查收！'),
            "keyword1"=>array('value' =>$ssmoney),
            "keyword2"=>array('value' =>date('Y-m-d H:m:s')),
            "remark"=>array('value' => ""),
        );
        $openid=m('member')->getopenid($userup['ssuid']);

        $account = WeAccount:: create($_W['acid']);//$this->createMobileUrl('person',array('op'=>'comein')
        $a = $account->sendTplNotice($openid['openid'], $config['tpl_notice4'], $data,'');

        /*********发送结束**********/
	}
	if($sssmoney && $userup['sssuid']){
		mc_credit_update($userup['sssuid'], 'credit2', $sssmoney, array(0));
		$data4 = array(
			'uid'=>$userup['sssuid'],
			'src_text'=>'收入',
			'data_name'=>'下级办理'.$name1.'提成',
			'src'=>$type,
			'order_money'=>$money,
			'type_text'=>'提成',
			'money'=>$sssmoney,
			'create_time'=>date('Y-m-d H:m:s',time()),
			'uniacid' => $me['uniacid'],
		);
		pdo_insert('xuan_zy_money', $data4);

        /*********发送提醒**********/
        $data  = array(
            "first"=>array( "value"=> '您的下级办理了'.$name1.'，您获得了'.$sssmoney.'元的提成奖励！已到账，请查收！'),
            "keyword1"=>array('value' =>$sssmoney),
            "keyword2"=>array('value' =>date('Y-m-d H:m:s')),
            "remark"=>array('value' => ""),
        );
        $openid=m('member')->getopenid($userup['sssuid']);

        $account = WeAccount:: create($_W['acid']);//$this->createMobileUrl('person',array('op'=>'comein')
        $a = $account->sendTplNotice($openid['openid'], $config['tpl_notice4'], $data,'');

        /*********发送结束**********/
	}
	if($type==1){
		$data5 = array(
			'status'=>3,
			'money'=>$money
		);
		pdo_update('xuan_zy_bankorder', $data5,array('id'=>$idd));
		/*升级检查 */

		/*$num=pdo_fetchcolumn("SELECT count(*) FROM ".tablename("xuan_zy_bankorder")." WHERE user_id=:id and status=3 ",array(":id"=>$uid));

		if($num>=$config['sj_zy'] && $me['level']==0){
			//升级专员
			$user_data = array(
				'level' => 1,
			);
			pdo_update('xuan_zy_person', $user_data, array('uid' => $uid));
		}*/


	}else{
		$data5 = array(
			'status'=>2,
			'loan_money'=>$money
		);
		pdo_update('xuan_zy_loadorder', $data5,array('id'=>$idd));
	}

	pdo_commit();
} catch (Exception $e) {
	pdo_rollback();
}

}
/**
 * 返回0则说明不提成
 */
function getrate($level,$slevel,$config){

		if($slevel && $slevel['level']>=$level ){
			if($slevel['level']==1){
				if($slevel['level']==$level){
					return $config['zy_zy'];
				}else{
					return $config['zy_tc2'];
				}
			}elseif($slevel['level']==2){
				if($slevel['level']==$level){
					return $config['jl_jl'];
				}else{
					return getrate2($level,$slevel['level'],$config);
				}
			}elseif($slevel['level']==3){
				if($slevel['level']==$level){
					return $config['yhj_yhj'];
				}else{
					return getrate2($level,$slevel['level'],$config);
				}
			}

		}else{
			return 0;
		}

}
function getrate2($level1,$level2,$config){
	if($level2==2){
		if($level1==0){
			return $config['jl_bk'];
		}elseif($level1==1){
			return $config['jl_zy'];
		}
	}elseif($level2==3){
		if($level1==0){
			return $config['yhj_bk'];
		}elseif($level1==1){
			return $config['yhj_zy'];
		}elseif($level1==2){
			return $config['yhj_jl'];
		}
	}
}